Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

372
Vistas
How do you set precision of decimal when there is an "E" involved within the number?

I want to trim my decimal into something like 8.063 instead of the original which is 8.0638304611694E-9. I have implemented a function for it but it doesn't work when there is E-9 in it. Which part should I modify??

public function setPrecision($number, $decimals = 0)
{
    $negation = ($number < 0) ? (-1) : 1;
    $coefficient = 10 ** $decimals;
    return $negation * floor((string)(abs($number) * $coefficient)) / $coefficient;
}

EDIT

The current implementation gave me 0 when I try to call the function.

setPrecision(8.0638304611694E-9, 3); // 0
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

In PHP, there are (at the moment of writing) 8519 builtin functions. One of them probably does the trick!

You could use log10() and round() in your function:

function setPrecision($number, $precision = 0)
{
    $exponent = floor(log10($number)) - 1;
    return round($number, -$exponent + $precision - 1);
}

over 4 years ago · Santiago Trujillo Denunciar

0

Relative rounding with a certain number of digits can easily be done with sprintf.

$round = (float)sprintf('%0.3E', 8.0638304611694E-9);
var_dump($round);  //float(8.064E-9)

On this basis I have this function which rounds float values with a certain relative decimal precision.

 /*
  * @return Float-Value with reduced precision
  * @param $floatValue: input (float)
  * @param $overallPrecision: 1..20 (default 10)
  */
  function roundPrecision($floatValue, $overallPrecision = 10)
  {
    $p = min(20,max(0,$overallPrecision-1));
    $f =(float)sprintf('%.'.$p.'e',$floatValue);
    return $f;
  }

example 1

  $float = 0.0000123456789;
  $newFloat = roundPrecision($float,5);
  printf('%0.10f',$newFloat);  //0.0000123460

example 2

  $float = 3456.7891234;
  $newFloat = roundPrecision($float,5);
  printf('%0.10f',$newFloat);  //3456.8000000000
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda